'''
@File    :   run.py.py
@Contact :   desufnocs@163.com
@des     :   fastapi入口文件

@Modify Time       @Author      @Version    @Desciption
------------      ----------    --------    -----------
2025/2/17 22:42   AssenImpact      1.0         None
'''
import os

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

from control import config as CONFIG
from .core import Middleware
from .core.Event import on_startup
from .core.Exception import http422_error_handler, HTTPException_error_handler
from .routers import control, file

if CONFIG.DEVELOPER_MODE:
    app = FastAPI(title="控制中心", description='局域网内设备控制主机', docs_url="/docs", redoc_url="/redoc")
else:
    app = FastAPI(title="控制中心", description='局域网内设备控制主机', docs_url=None, redoc_url=None)
# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"]
)
# HOST拦截中间件
app.add_middleware(Middleware.IPMiddleware, allow_origins=CONFIG.ALLOW_HOSTS)
# 请求头拦截中间件
app.add_middleware(Middleware.VerifyTokenMiddleware, access_header={"x-access-key"})

app.add_event_handler("startup", on_startup)
# 替换默认异常捕获
app.add_exception_handler(HTTPException, HTTPException_error_handler)
app.add_exception_handler(RequestValidationError, http422_error_handler)

app.include_router(control.router)
app.include_router(file.router)

static_path = os.path.join(CONFIG.BASE_DIR, "static")
if os.path.exists(static_path):
    app.mount("/", StaticFiles(directory=os.path.join(CONFIG.BASE_DIR, "static"), html=True))
